import edge_tts
import asyncio
import os

async def generate_speech(text, voice="zh-CN-YunxiNeural", output_file="output.mp3"):
    try:
        communicate = edge_tts.Communicate(text, voice)
        await communicate.save(output_file)
        print(f"语音已保存到: {output_file}")
        return True
    except Exception as e:
        print(f"语音生成失败: {str(e)}")
        return False

def play_audio(file_path):
    """播放生成的音频"""
    # 需要先安装 mpg123: sudo apt install mpg123
    os.system(f"mpg123 -q {file_path}")

# 使用示例
if __name__ == "__main__":
    text = "树莓派语音测试成功！"
    success = asyncio.run(generate_speech(text,"zh-CN-XiaoxiaoNeural"))
    
    if success:
        play_audio("output.mp3")
        os.remove("output.mp3")  # 清理临时文件